﻿using SeeSharpTools.JY.DSP.Fundamental;
using SeeSharpTools.JY.DSP.Utility.Filter1D;
using SeeSharpTools.JY.File;
using Sunny.UI;
using System;
using System.IO;

namespace SeeSharpTools.Demo
{
    public partial class FormNotch : UIPage
    {
        public FormNotch()
        {
            InitializeComponent();
        }

        private void FormNotch_Load(object sender, EventArgs e)
        {
            DirectoryInfo directory = new DirectoryInfo(Environment.CurrentDirectory);
            string path = directory.Parent.Parent.FullName + "\\ExampleData\\Filter\\openloop60hertz.csv";

            // 读取60 Hz 电力线噪声叠加的交流电压值
            double[,] data = CsvHandler.Read<double>(path);
            double[] x = new double[data.GetLength(0)];
            for (int i = 0; i < x.Length; i++)
            {
                x[i] = data[i, 0];
            }

            double sampleRate = 1000;

            // 使用二阶陷波器消除60 Hz 噪声
            var (b, a) = IIRDesign.IIRNotch(60, 5, sampleRate);
            var (mag, _, f) = IIRAnalysis.Bode(b, a, sampleRate);
            easyChartX_Mag.Plot(f, mag);
            var (gd, _) = IIRAnalysis.GroupDelay(b, a, sampleRate);
            easyChartX_GrpDelay.Plot(f, gd);

            // 使用零相位滤波器进行滤波，以补偿滤波器延迟
            double[] y = IIRFiltering.ZeroPhaseFilter(b, a, x);
            double[,] combinedSignal = new double[2, x.Length];
            for (int i = 0; i < x.Length; i++)
            {
                combinedSignal[0, i] = x[i];
                combinedSignal[1, i] = y[i];
            }

            easyChartX_Signal.Plot(combinedSignal, 0, 1 / sampleRate);
            easyChartX_Signal.Series[0].Name = "滤波前";
            easyChartX_Signal.Series[1].Name = "滤波后";

            // 在频谱中观察到60 Hz的噪声已经被滤除
            double[,] spectrum = new double[2, x.Length / 2];
            double[] sp1 = new double[x.Length / 2];
            double[] sp2 = new double[x.Length / 2];
            SeeSharpTools.JY.DSP.Fundamental.Spectrum.PowerSpectrum(x, sampleRate, ref sp1, out double df, SpectrumUnits.dBV);
            SeeSharpTools.JY.DSP.Fundamental.Spectrum.PowerSpectrum(y, sampleRate, ref sp2, out df, SpectrumUnits.dBV);
            for (int i = 0; i < sp1.Length; i++)
            {
                spectrum[0, i] = sp1[i];
                spectrum[1, i] = sp2[i];
            }
            easyChartX_Spectrum.Plot(spectrum, 0, df);
            easyChartX_Spectrum.Series[0].Name = "滤波前";
            easyChartX_Spectrum.Series[1].Name = "滤波后";
        }
    }
}